package main

import (
	"bufio"
	"dempsey/fileUpload/utils/proto"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"strconv"
)

var listen net.Listener

func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:30000")
	if err != nil {
		fmt.Println("listen failed, err:", err)
		return
	}
	defer listen.Close()

	http.HandleFunc("/uploadFile", handler)
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	// 1.文件接收
	defer r.Body.Close()
	r.ParseForm()
	// 打印form数据
	fmt.Println(r.PostForm)
	fileName, hash, num := r.PostForm.Get("fileName"), r.PostForm.Get("fileHash"), r.PostForm.Get("fileNum")
	fileHash := []byte(hash)
	fileNum, err := strconv.Atoi(num)
	if err != nil {
		log.Println("获取 fileNum 失败")
	}
	fmt.Printf("Send: fileName:%v,  bigHash:%x, num:%v\n", fileName, fileHash, num)

	// 开携程，做 waitGroup，或者 ctx
	for i := 0; i < fileNum; i++ {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("accept failed, err:", err)
			continue
		}
		go getFile(conn, fileName)
	}

	answer := `{"status": "ok"}`
	w.Write([]byte(answer))

	// 1.1读取文件数，开启多线程接收
	// 1.2校验文件 hash，一旦失败，直接结束

	// 2.文件合并
	// 2.校验 hash

	// 3.起协程传 redis

	// 4.完成

}

func getFile(conn net.Conn, fileName string) {
	defer conn.Close()

	reader := bufio.NewReader(conn)
	for {
		gotFileName, gotHash, gotMessage, err := proto.Decode(reader)
		if err == io.EOF {
			return
		}
		if err != nil {
			fmt.Println("decode msg failed, err:", err)
			return
		}
		fmt.Println("收到client发来的数据：", gotFileName, gotHash, gotMessage)
	}
}
